const http = require("http")
const path = require("path")
const fs = require("fs")
const querystring = require("querystring")
const express = require("express")
const bodyParser = require("body-parser")
const cookieParser = require('cookie-parser')
const app = express()




app.use(bodyParser.urlencoded({
  extended: true
}))

app.use(express.static(path.join(__dirname, "dist")))
app.use(cookieParser())

app.post("/api/*", (req, res) => {
    const postData = querystring.stringify(req.body)
    let   cookies  = querystring.stringify(req.cookies, ';')
    // let cookies = ((obj)=>{
    //     let str = ""
    //     for (let key in obj) {
    //         str += `${key}=${encodeURIComponent(obj[key])};`
    //     }
    //     str = str.slice(0, -1)

    //     return str

    // })(req.cookies)

    const proxyRequest = http.request({
        host: process.argv[2] || "unionapitest.jinghao.com",
        port: process.argv[3] || 80,
        path: req.path,
        method: req.method,
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "Content-Length": Buffer.byteLength(postData),
            "Cookie": cookies
        }
    }, (proxyResponse) => {
        proxyResponse.headers['set-cookie'] && (proxyResponse.headers['set-cookie'] = proxyResponse.headers['set-cookie'].map(v => v.replace(/domain\=[^\;]+/gim, 'domain=localhost')));

        res.writeHead(proxyResponse.statusCode, proxyResponse.headers)

        proxyResponse.pipe(res)
    })

    req.pipe(proxyRequest)
    proxyRequest.write(postData)
    proxyRequest.end()

})

app.listen(8800)
